package layers.ants;

import layers.agents.PackageAgent;
import layers.physical.Crossroad;
import layers.physical.Path;
import layers.physical.Road;

public class DeliveryAnt extends HopAnt {

	public static final int INITIALHOPS = 250;
	private Crossroad destination;

	public DeliveryAnt(Crossroad crossroad, Crossroad destination, PackageAgent pa, Path path, int initialHops, long traveledDistance) {
		super(crossroad, pa, path, initialHops, traveledDistance);
		this.destination =destination;
	}

	public void processAntTick() {
		//increase hop
		decreaseRemainingHops();
		increaseTraveledDistance(getLengthOfLastRoad());
		if(getRemainingHops() > 0)
			searchDeliveryLocation();
		else
			die();
	}

	private void searchDeliveryLocation() {
		//get useful vars
		int truckId = this.getAgent().getId();
		Crossroad crossroad = getCrossroad();
		if(crossroad.equals(destination)){
			reportBackToPackageAgent();
			die();
		}
		//die if an similar ant had already been on this crossroad
		else if(crossroad.containsBetterDeliveryMark(truckId, getTraveledDistance())){
			die();
		}
		//drop mark and start following pheromones towards package if there are any
		else{
			dropDeliveryMark(truckId, crossroad);
			putClonesOnRoads();
			die();

		}
	}

	private void reportBackToPackageAgent() {
		((PackageAgent) this.getAgent()).proposeDelivery(this.getPath());
	}

	protected void dropDeliveryMark(int truckId, Crossroad crossroad) {
		Mark mark = new Mark(truckId, getRemainingHops(), getTraveledDistance());
		crossroad.dropDeliveryAntMark(mark);
	}


	public Crossroad getDestination() {
		return destination;
	}

	protected void putClonesOnRoads() {
		for(Road road : getCrossroad().getOutgoingConnections()){
			Crossroad nextCrossroad = road.getOtherConnector(getCrossroad());
			if(!this.getPath().contains(nextCrossroad) && 
					!nextCrossroad.containsBetterDeliveryMark(
							this.getAgent().getId(), getTraveledDistance() + road.getLength())){
				DeliveryAnt ant = new DeliveryAnt(
						nextCrossroad, 
						destination,
						(PackageAgent) getAgent(),
						(Path) getPath().getClone(),
						getRemainingHops(), 
						getTraveledDistance());
				ant.setRoadLastTraveled(road);
			}
		}
	}
}
